package com.example.controlcarappv2;

import java.util.ArrayList;
import java.util.List;

import com.example.controlcarappv2.R;
import com.example.controlcarappv2.BluetoothService;
import com.example.controlcarappv2.DeviceListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private BluetoothAdapter meuBluetooth = null;
	private BluetoothService meuServico = null;
	private ControlaCarro controla = new ControlaCarro();
	
	// Intent request codes
	private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;
	
	// Message types sent from the BluetoothChatService Handler
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;
	
	// Key names received from the BluetoothChatService Handler
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// Get local Bluetooth adapter
		meuBluetooth = BluetoothAdapter.getDefaultAdapter();

		// If the adapter is null, then Bluetooth is not supported
		if (meuBluetooth == null) {
			Toast.makeText(this, "Bluetooth is not available",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

	}
	
	@Override
	protected void onStart(){
		super.onStart();
		
		// Se o BT nao esta ativo, chama a Intent para ativar.
		if (!meuBluetooth.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		} else {
			if (meuServico == null){}
				setup();
		}
	}
	
	private void setup(){
		meuServico = new BluetoothService(this, meuHandler);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			// Retorna o Device selecionado para conexao.
			if (resultCode == Activity.RESULT_OK) {
				// Pega o MAC do Device
				String address = data.getExtras().getString(
						DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				// Cria um Objeto Bluetooth.
				BluetoothDevice device = meuBluetooth.getRemoteDevice(address);
				meuServico.connect(device);
			}
			break;
		case REQUEST_ENABLE_BT:
			if (resultCode == Activity.RESULT_OK) {
				setup();
			} else {
				Toast.makeText(this, R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Cria Menu para Conectar os dispositivos.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_menu, menu);
		return true;

	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.scan:
			// Launch the DeviceListActivity to see devices and do scan
			Intent serverIntent = new Intent(this, DeviceListActivity.class);
			startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			return true;
		case R.id.discoverable:
			// Ensure this device is discoverable by others
			ensureDiscoverable();
			return true;
		}
		return false;
	}
	
	private final Handler meuHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothService.STATE_CONNECTED:
					Toast.makeText(getApplicationContext(), "Conectado", Toast.LENGTH_SHORT).show();
					break;
				case BluetoothService.STATE_CONNECTING:
					Toast.makeText(getApplicationContext(), "Conectando", Toast.LENGTH_SHORT).show();
					break;
				case BluetoothService.STATE_LISTEN:
				case BluetoothService.STATE_NONE:
					Toast.makeText(getApplicationContext(), "Nao Conectado", Toast.LENGTH_SHORT).show();
					break;
				}
				break;
			case MESSAGE_WRITE:
				byte[] writeBuf = (byte[]) msg.obj;
				// construct a string from the buffer
				String writeMessage = new String(writeBuf);
				Toast.makeText(getApplicationContext(), "Mensagem Enviada" + writeMessage, Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				Toast.makeText(getApplicationContext(), "Mensagem Recebida: " + readBuf, Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_DEVICE_NAME:
				// save the connected device's name
				Toast.makeText(getApplicationContext(),
						"Connected to " + msg.getData().getString(DEVICE_NAME),
						Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_TOAST:
				Toast.makeText(getApplicationContext(),
						msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
						.show();
				break;
			}
		}
	};
	
	private void ensureDiscoverable() {
		if (meuBluetooth.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
	}
	
	public void btnLeft(View v){
		String s = "a";
		meuServico.write(s.getBytes());
	}
	
	public void btnUp(View v){
		String s = "w";
		meuServico.write(s.getBytes());
	}
	
	public void btnRight(View v){
		String s = "d";
		meuServico.write(s.getBytes());
	}
	
	public void btnDown(View v){
		String s = "s";
		meuServico.write(s.getBytes());
	}
	
	public void btnReto(View v){
		String s = "q";
		meuServico.write(s.getBytes());
	}
	
	public void btnPara(View v){
		String s = "e";
		meuServico.write(s.getBytes());
	}
	
	public void btnResolve(View v){		
		try {
		Labirinto novo = new Labirinto();
		novo.geraLabirinto();
		
		algoritmoSolucao novaSolucao = new algoritmoSolucao();
		
		novaSolucao.resolveLabirinto(novo);
		
		if (novaSolucao.resolvido){
			List<String> movimentos = new ArrayList<String>();
			
			for(Labirinto a : novaSolucao.closedList){
				if (a.acaoRealizada != null)
					movimentos.add(a.acaoRealizada.toString());
			}
			
			for(String s : movimentos){
				Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
				if (s == "Move para Esqu."){
					controla.esquerda(meuServico);
				}
				else if (s == "Move para Dire."){
					controla.direita(meuServico);
				}
				else if (s == "Move para Cima."){
					controla.frente(meuServico);
				}
				else if (s == "Move para Baixo"){
					controla.atras(meuServico);
				}
			}
			
			Toast.makeText(getApplicationContext(), "Resolvido !", Toast.LENGTH_SHORT).show();
		}
		else
			Toast.makeText(getApplicationContext(), "Nao Resolvido !", Toast.LENGTH_SHORT).show();
		}
		catch (Exception e){
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

}
